package com.spukmk3me.animatorpack.pack0;

import com.spukmk3me.scene.Animator;
import com.spukmk3me.scene.Node;

public class RotationAnimator extends Animator
{
    public RotationAnimator()
    {
        m_running = false;
    }
    
    @Override
    public void animate( int time )
    {
        if ( !m_running )
            return;
        
        float delta = ((float)time / 0x00010000) * m_rotSpeed;

        if ( m_rotateAmount >= 0 )
        {
            float absDelta = Math.min( m_rotateAmount, Math.abs( delta ) );
            
            m_rotateAmount -= absDelta;
            m_running = m_rotateAmount > 0;
            
            if ( delta < 0 )
                delta = -absDelta;
            else
                delta = absDelta;
        }
        
        m_currentAngle += delta;
        
        while ( m_currentAngle >= Math.PI * 2 )
            m_currentAngle -= Math.PI * 2;
        
        while ( m_currentAngle <= -Math.PI * 2 )
            m_currentAngle += Math.PI * 2;
        
        applyToNode();
    }

    protected void onNodePrepareToChange( Node newNode )
    {
        
    }

    protected void onNodeChanged()
    {
        if ( getNode() == null )
            m_running = false;
        else
        {
            applyToNode();
            m_running = true;
        }
    }
    
    public boolean isAnimating()
    {
        if ( getNode() == null )
            return false;
        
        return m_running;
    }
    
    /**
     * 
     * @param centerX
     * @param centerY
     * @param startAngle
     * @param rotateAmount Negative value for infinite rotation
     * @param rotationSpeed
     * @param translateX
     * @param translateY
     */
    public void setupRotation( float centerX, float centerY,
        float startAngle, float rotateAmount, float rotationSpeed, float translateX, float translateY )
    {
        m_centerX = centerX;
        m_centerY = centerY;
        m_currentAngle = startAngle;
        m_rotateAmount = rotateAmount;
        m_rotSpeed = rotationSpeed;
        m_tx = translateX + centerX;
        m_ty = translateY + centerY;
        m_running = false;
        
        if ( getNode() != null )
        {
            applyToNode();
            m_running = true;
        }
    }
    
    private void applyToNode()
    {
        Node node = getNode();
        
        node.reset();
        node.setPivot( m_centerX, m_centerY );
        node.setRot( m_currentAngle );
        node.setTrans( m_tx, m_ty );
    }
    
    private float   m_centerX, m_centerY, m_currentAngle, m_rotateAmount, m_rotSpeed, m_tx, m_ty;
    private boolean m_running;
}
